<template>
  <div class='tinymce'>
    <h1>
      <el-row>
        <el-col :span="5">
          <span v-if="dataArtice">修改文章</span>
          <span v-else>添加文章</span>
          <el-button class="addBtn" @click="goBack">返回</el-button>
        </el-col>
        <el-col :span="19" style="text-align:right">
           <el-button v-if="article" type="primary" @click="submitArticle('formAling')">修改文章</el-button>
           <el-button v-else type="success" @click="submitArticle('formAling')">保存</el-button>
        </el-col>
      </el-row>
    </h1>
    <div>
      <el-form :inline="true"  :rules="form1" ref="form1" :model="form1">
        <el-form-item label="分类">
          <el-select  v-model="form1.value" placeholder="请选择" style="width:120px">
          <el-option
            v-for="item in form1.options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form1.line" placeholder="请选择状态" style="width:120px">
            <el-option v-for="item in form1.lines" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布者ID">
          <el-select v-model="form1.hlpe" placeholder="请选择ID" style="width:120px">
           <el-option v-for="item in form1.hlpes" :key="item.userId" :label="item.userNick" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
         <el-form-item  prop="type">
            <el-checkbox v-model="form1.type"  label="首页推荐文章" name="type"></el-checkbox>
        </el-form-item>
        <el-form-item label="喜欢" v-if="dataArtice">
          <el-input v-model="form1.stars" style="width:80px" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="点击量" v-if="dataArtice">
          <el-input v-model="form1.page_view" style="width:80px" placeholder="请输入内容"></el-input>
        </el-form-item>
        
      </el-form>
     <el-form  label-width="80px" :rules="aling" ref="formAling" :model="formLabelAlign">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="formLabelAlign.title"></el-input>
        </el-form-item>
      </el-form>
      <el-row>
        <el-col :span="12">
        
        <el-form :inline="true"  :rules="form2" ref="form2" :model="form2">
          <el-form-item label="文章描述" prop="desc">
            <el-input style="width:300px;height:146px" type="textarea" v-model="form2.desc"></el-input>
          </el-form-item>
         </el-form>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="18">
             <span style="font-weight:normal;font-size:14px">封面图：</span>
              <el-upload
                style="display:inline-block"
                :action="action"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-success="handleOkTitle"
                :data="postData"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-col>
            <el-col :span="6">
              <img :src="articleThum" style="width:120px;height:150px"/>
            </el-col>
          </el-row>
        </el-col>

      </el-row>
      <el-row>
        <div style="padding-left:20px;">
          <div class="initbox">
            <el-button class="initBtn" @click="upImageFun">图</el-button>
            <editor id='tinymce' v-model='tinymceHtml' :init='init'> </editor>
            
          </div>

          <el-button type="success" @click="submitArticle('formAling')">保存文章</el-button>
        </div>
      </el-row>
    
    </div>
    <el-dialog :visible.sync="imgstuts">
      <el-upload
        class="upload-demo"
        :action="action"
        :on-preview="handlePreview"
        :on-remove="handleRemoveEidt"
        :on-success="handleOkContent"
        ref="upload"
        :data="postData"
        multiple
       
        >
        <el-button size="small" type="primary">添加图片</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="backFun">取 消</el-button>
        <el-button type="primary" @click="apendHtml">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {mapActions,mapMutations,mapGetters,mapState} from 'vuex'
import Http from '@/Http/Http'
import qnUrl from '@/Http/qiniuUrl'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'

export default {
  name: 'tinymce',
  props:['dataArtice'],
  data () {
    const title = (rule,value,callback) => {
      if (value === '') {
        callback(new Error('请输入标题'))
      } else {
        callback()
      }
    }
    return {
      action:qnUrl,//七牛的上传地址
      imgIndex:'',
      imgUrl:'', // 
      postData:{
        token:'',
      },
      articleThum:'',// 封面图
      tokenimgUrl:'', //域名地址
      form2:{
        desc:'',
      },
      dialogImageUrl: '',
      dialogVisible: false,
       form1:{
        page_view:0,
        stars:0,
        hlpe:10001,
        line:1,
        value:0,
        hlpes:[
          {value:10001,label:'无C端用户'},
        ],
        lines:[
          {value:1,label:'上线'},
          {value:2,label:'下线'}
        ],
        type:false,

        options:[{
          value:0,
          label:'全部'
        },{
          value:1,
          label:'牙齿矫正'
        },{
          value:2,
          label:'种植牙'
        },{
          value:3,
          label:'口腔健康'
        },{
          value:4,
          label:'儿童口腔'
        }],
      },
      formLabelAlign:{
        title:'',
        
      },
      aling:{
        title:[
          {validator:title,trigger:'blur'}
        ]
      },

      imgstuts:false, //富文本编辑器部分
      tinymceHtml:'',
      fileList:[],
      init: {
        language_url: '/static/tinymce/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/static/tinymce/skins/lightgray',
        height: 300,
        plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
        toolbar:
          'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image | removeformat',
        branding: false
      }
    }
    
  },

  computed: {
    ...mapState(['article'])  
  },
  mounted () {
    
  },
  created() {
    this.getToken()
  },
  methods:{
    getToken() {
      if (this.dataArtice) {
        this.form1.value = this.dataArtice.type?this.dataArtice.type:0  //类型   stars
        this.form1.page_view  = this.dataArtice.countRead?this.dataArtice.countRead:0 
        this.form1.stars = this.dataArtice.countLike?this.dataArtice.countLike:0 
        if(this.dataArtice.isRecommend){
          this.form1.type = true
        } else {
          this.form1.type = false
        }   // 推荐 
        this.form1.hlpe = this.dataArtice.articleUser.userId //发布者id 
        // this.form1.hlpe = this.dataArtice.articleUserid?this.dataArtice.articleUserid:10001 //发布者id 
        this.form1.line = this.dataArtice.articleStatus //状态
        this.formLabelAlign.title = this.dataArtice.articleTitle //标题
        this.articleThum = this.dataArtice.articleThum //封面图
        this.tinymceHtml = this.dataArtice.articleContent.replace(/100%/g,'50%')
      }
      Http.getCuser({})
      .then( res => {
        this.form1.hlpes  = res.data.data;
        if(!this.dataArtice){
          this.form1.hlpe = res.data.data[0].userId
        }
        
      })
      .catch( error => {
      })


      Http.QiniuToken({})
      .then( res => {
        this.postData.token = res.data.data.uptoken;
        this.tokenimgUrl = res.data.data.domain
      })
      .catch( error => {
        this.$router.push('/')
      })
    },
    handleRemove(file, fileList) {
    },
    handlePictureCardPreview(event, file, fileList) {
    },
    handleOkTitle(responed) {
      this.articleThum = `http://${this.tokenimgUrl}/${responed.key}`
    },
   
    submitArticle(val) {
      
      this.$refs[val].validate((valid) => {
       
        if (valid) {
          if (!this.articleThum) {
            this.$message.error('请上传文章封面图')
            return
          }
          // const reg = /function|script|alert|a()|iframe|onload/;

          // if (reg.test(this.tinymceHtml)){
          //   this.$message.error('不能出现敏感关键词')
          //   return
          // }
         
          const isRe = this.form1.type?1:0;
          const articleContent = this.tinymceHtml.replace(/50%/g,'100%');
          const param = {
            "articleTitle":this.formLabelAlign.title,  //文章标题
            "articleThum":this.articleThum,  //封面
            "articleStatus":this.form1.line,  //上线状态 
            "articleContent":articleContent, // 文章内容  实体列表 
            "articleUserid":this.form1.hlpe,
           
            "isRecommend":isRe, //推荐
            "topic":{
              "id":this.form1.value //分类 id 
            }
          }
          
          if (this.dataArtice) {
            param.articleId = this.dataArtice.articleId
            param.countLike = this.form1.stars;
            param.countRead = this.form1.page_view;
            this.postEditAriticeFun(param)
          } else {
            this.addAriticeFun(param)
          }
          
        } else {
          this.$message.error('请填写标题')
        }
      })
      
    },
    addAriticeFun(param) {
      Http.addAritice(param)
        .then( res => {
          if( res.data.code == 200 ){
            this.$message.success('文章发布成功')
            this.goBack()         
          } else if(res.data.code == -1003) {
            this.$message.error(`请求失败原因：${res.data.message}`)
            this.$router.push('/')
          }
        })
        .catch( error => {
          this.$message.error('服务器请求失败')
        })
    },
    postEditAriticeFun(param) {
      Http.postEditAritice(param)
      .then( res => {
        if( res.data.code == 200 ){
          this.$message.success('文章修改成功')
          this.goBack()         
        } else if(res.data.code == -1003) {
          this.$message.error(`请求失败原因：${res.data.message}`)
          this.$router.push('/')
        }
      })
      .catch( error => {
        this.$message.error('服务器请求失败')
      })
    },
    goBack(){
      this.$emit('breakFun')
    },
    
    //富文本编辑器部分
    upImageFun(){
      this.imgstuts = true
    },
    handleRemoveEidt(file, fileList) {
    },
    handlePreview(file) {
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    handleOkContent(responed){
      this.fileList.push(`http://${this.tokenimgUrl}/${responed.key}`)
    },
    backFun(){
      this.imgstuts = false;
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    },
    apendHtml(){
      let arrHtml='';
      this.fileList.forEach(item => {
        arrHtml += `<img style="width:50%" src="${item}" alt=""/>`;
      })
      this.tinymceHtml = `${this.tinymceHtml}${arrHtml}`;
      this.imgstuts = false
      this.fileList =[]
      this.$refs.upload.clearFiles(); 
    }
  },
  components: {
    Editor,
  }
}
</script>
<style>
.el-textarea__inner{
  height:146px
}
.initbox{
  position: relative;
}
.initBtn{
  position: absolute;
  opacity: 0;
  position: absolute;
  z-index: 2;
  top: 36px;
  left: 786px;
  width: 30px;
  padding: 0;
  height: 33px;
  border: 1px solid red;
}

#tinymce_ifr{
  height:500px !important
}
</style>
